//
//  WSLoginController.m
//  BaseProject
//
//  Created by karong on 2023/6/12.
//

#import "WSLoginController.h"

#import <Firebase.h>
#import <FirebaseAuth/FirebaseAuth.h>
#import <AuthenticationServices/AuthenticationServices.h>
#import "CTMediator+StartAction.h"
#import <GoogleSignIn/GoogleSignIn.h>
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <FBSDKLoginKit/FBSDKLoginKit.h>
#import "WSUserRequest.h"
#import "BaseTabBarController.h"
#import "UIButton+GKCategory.h"
#import <UMShare/UMShare.h>

@interface WSLoginController () <ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding>

@property (weak, nonatomic) IBOutlet UIView *appleView;
@property (weak, nonatomic) IBOutlet UIView *appIdView;
@property (weak, nonatomic) IBOutlet UIView *googleView;
@property (weak, nonatomic) IBOutlet UIView *facebookView;
@property (weak, nonatomic) IBOutlet UIButton *fastLoginBtn;
@property (weak, nonatomic) IBOutlet UIButton *googleLoginBtn;
@property (weak, nonatomic) IBOutlet UIButton *facebookLoginBtn;
@property (weak, nonatomic) IBOutlet UIButton *checkBoxBtn;
@property (weak, nonatomic) IBOutlet UIView *mainView;
@property (strong, nonatomic) NSString *appleNonce;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *fastLoginTop;

@end

@implementation WSLoginController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self layoutView];
}


- (void)layoutView {
    NSInteger btnCount = 0;
    self.googleView.hidden = NO;
    self.facebookView.hidden = NO;
    
    if (@available(iOS 13.0, *)) {
        btnCount ++;
        [self createAppleLoginView];
    }
    else {
        [self.appleView removeFromSuperview];
    }
//    if (appConfig.startConfig.google_login == 1) {
//        self.googleView.hidden = NO;
//    }
//    else {
//        [self.googleView removeFromSuperview];
//    }
//    if (appConfig.startConfig.facebook_login == 1) {
//        self.facebookView.hidden = NO;
//    }
//    else {
//        [self.facebookView removeFromSuperview];
//    }
//    btnCount += MIN(appConfig.startConfig.facebook_login, 1);
//    btnCount += MIN(appConfig.startConfig.google_login, 1);
    btnCount += 1;
    btnCount += 1;

    self.fastLoginTop.constant = 80 + (24 + 44) * btnCount;
    [self.view uploadLayout];
    [self layoutBottomLabel];
}

- (IBAction)touchTiaoGuo:(id)sender {
//    BaseNavigationController * nav = [[BaseNavigationController alloc]initWithRootViewController:[BaseTabBarController new]];
//    nav.navigationBarHidden = YES;
//    typedef void (^Animation)(void);
//    UIWindow* window = [UIApplication sharedApplication].keyWindow;
//    window.rootViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
//    Animation animation = ^{
//        BOOL oldState = [UIView areAnimationsEnabled];
//        [UIView setAnimationsEnabled:NO];
//        [UIApplication sharedApplication].keyWindow.rootViewController = nav;
//        [UIView setAnimationsEnabled:oldState];
//    };
//    [UIView transitionWithView:window
//                      duration:0.5f
//                       options:UIViewAnimationOptionTransitionCrossDissolve
//                    animations:animation
//                    completion:^(BOOL finished) {
//        if (finished) {
//        }
//    }
//    ];
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)layoutBottomLabel {
    YYLabel *label = [[YYLabel alloc] init];
    label.numberOfLines = 0;
    label.textAlignment = NSTextAlignmentCenter;
    [self.mainView addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.checkBoxBtn.mas_right).offset(4);
        make.top.bottom.right.mas_equalTo(self.mainView);
    }];
    
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.alignment = NSTextAlignmentCenter;
    style.lineBreakMode = NSLineBreakByWordWrapping;
    NSString *text = APPLocalized(@"點擊登錄表示已同意短劇星《用戶協議》、《隱私政策》和《第三方Ushare服務和隱私條款》");
    NSMutableAttributedString *attrText = [[NSMutableAttributedString alloc] initWithString:text
                                                                                 attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:12], NSParagraphStyleAttributeName: style, NSForegroundColorAttributeName: UIColor.font_gray_999999}];
    
    NSString *string1 = APPLocalized(@"《用戶協議》");
    NSRange range1 = [text rangeOfString:string1];
    [attrText addAttributes:@{NSUnderlineStyleAttributeName: @(1)} range:range1];
    [attrText setTextHighlightRange:range1 color:UIColor.font_yellow_FCB625 backgroundColor:nil tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        UIViewController * target = [[CTMediator sharedInstance]ct_showWebWithUrl:API_CHARONTV_AGREEMENT_USER titleStr:@"用戶協議" showNav:YES closeHandle:^{}];
        [self.navigationController pushViewController:target animated:YES];
    }];
    
    NSString *string2 = APPLocalized(@"《隱私政策》");
    NSRange range2 = [text rangeOfString:string2];
    [attrText addAttributes:@{NSUnderlineStyleAttributeName: @(1)} range:range2];
    [attrText setTextHighlightRange:range2 color:UIColor.font_yellow_FCB625 backgroundColor:nil tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        UIViewController * target = [[CTMediator sharedInstance]ct_showWebWithUrl:API_CHARONTV_AGREEMENT_PRIVACY titleStr:@"隱私政策" showNav:YES closeHandle:^{}];
        [self.navigationController pushViewController:target animated:YES];
    }];
    
    NSString *string3 = APPLocalized(@"《第三方Ushare服務和隱私條款》");
    NSRange range3 = [text rangeOfString:string3];
    [attrText addAttributes:@{NSUnderlineStyleAttributeName: @(1)} range:range3];
    [attrText setTextHighlightRange:range3 color:UIColor.font_yellow_FCB625 backgroundColor:nil tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        UIViewController * target = [[CTMediator sharedInstance]ct_showWebWithUrl:API_CHARONTV_AGREEMENT_USHARE titleStr:@"第三方Ushare服務和隱私條款" showNav:YES closeHandle:^{}];
        [self.navigationController pushViewController:target animated:YES];
    }];
    label.attributedText = attrText;
    [self.checkBoxBtn setEnlargeEdge:40];
}

- (void)createAppleLoginView {
    if (@available(iOS 13.0, *)) {
        ASAuthorizationAppleIDButton *appleIDButton = [[ASAuthorizationAppleIDButton alloc] initWithAuthorizationButtonType:ASAuthorizationAppleIDButtonTypeSignIn authorizationButtonStyle:ASAuthorizationAppleIDButtonStyleWhite];
        appleIDButton.frame = CGRectMake(0, 0, kScreenWidth - 40, 44);
        appleIDButton.layer.masksToBounds = YES;
        appleIDButton.layer.cornerRadius = 22;
        appleIDButton.tag = 10000;
        [appleIDButton addTarget:self action:@selector(appleLoginAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.appIdView addSubview:appleIDButton];

    }
}

- (void)logincharonTV_Request {
    WeakSelf
    [WSUserRequest logincharonTV_WithSuccess:^(id obj) {
        [WSToast dismiss];
//        UIViewController * target = [[CTMediator sharedInstance]ct_showSelectSex];
//        [weakSelf.navigationController pushViewController:target animated:YES];
        [[NSNotificationCenter defaultCenter]postNotificationName:WSRefreshUserInfoNotification object:nil];
        [self dismissViewControllerAnimated:YES completion:nil];
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {

    }];
}


//游客登錄
- (void)visitorRegist:(NSString *)userName password:(NSString *)password{
    [[FIRAuth auth]signOut:nil];
    [appUserCenter logOut];
    WeakSelf
    [[FIRAuth auth] signInWithEmail:userName
                           password:password
                         completion:^(FIRAuthDataResult * _Nullable authResult,
                                      NSError * _Nullable error) {
        if (error) {
            [WSToast simple:error.localizedDescription];
        }else{
            FIRUser *user = authResult.user;
            [user getIDTokenWithCompletion:^(NSString * _Nullable token, NSError * _Nullable error) {
                appUserCenter.qtoken = token;
                [weakSelf logincharonTV_Request];
            }];
        }
    }];
}

- (IBAction)fastLoginLoginAction:(id)sender {
    if (!self.checkBoxBtn.selected) {
        [WSToast simple:APPLocalized(@"請先閱讀並同意《用戶協議》，《隱私政策》和《第三方Ushare服務和隱私條款》")];
        return;
    }
//    appUserCenter.qtoken = @"eyJhbGciOiJSUzI1NiIsImtpZCI6ImM2MGI5ZGUwODBmZmFmYmZjMTgzMzllY2Q0NGFjNzdmN2ZhNGU4ZDMiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL3NlY3VyZXRva2VuLmdvb2dsZS5jb20vcGxhbmV0LXR2LTNkZTg2IiwiYXVkIjoicGxhbmV0LXR2LTNkZTg2IiwiYXV0aF90aW1lIjoxNjkzMzY2MTgzLCJ1c2VyX2lkIjoiaG1LOWhESFd5VmNFc1JOWWlMNTlUYkFHVFZxMSIsInN1YiI6ImhtSzloREhXeVZjRXNSTllpTDU5VGJBR1RWcTEiLCJpYXQiOjE2OTMzNjYxODMsImV4cCI6MTY5MzM2OTc4MywiZW1haWwiOiIzZGU0OWIzOS0yOTIxLTRkODktYWY4Ni1kZTJlZTA1YmFiOTdAY2hhcm9udHZhcHAuY29tIiwiZW1haWxfdmVyaWZpZWQiOmZhbHNlLCJmaXJlYmFzZSI6eyJpZGVudGl0aWVzIjp7ImVtYWlsIjpbIjNkZTQ5YjM5LTI5MjEtNGQ4OS1hZjg2LWRlMmVlMDViYWI5N0BjaGFyb250dmFwcC5jb20iXX0sInNpZ25faW5fcHJvdmlkZXIiOiJwYXNzd29yZCJ9fQ.obBVn2y8psmnbNzVuU36O4V4TyB-2namyA7zXeYi2t1_hK0n2cLfZEZ7pK4cIObU0Xw-uN1PD4WDRIJzHvX2iVpZmUebXCz_iNESE3aq_wmwechk5UPjj1kvRrBShnoSj8BIHRIm1l1RYDQVh48UfKsAzhhL1kE3omYz1tzMIvSdWQ04Cvd0vOHPNWcMbLiEWx5PLzvEWKBfjjNjErfeHkyKUanNCvs0elmZMzMnK1cgD6pa_OUd8RxNBBp7SEznQC0gNVQSH3F_BWhGj77tnAzvH0HUDbYm7JAp9bGrrj_OMO2wpxNc5gfsFAu6nAjjbzhKHjKyyVEcprnTRGOo7A";
//    [self logincharonTV_Request];
//    return;
    [WSToast loadingFull];
    [[FIRAuth auth]signOut:nil];
    [appUserCenter logOut];
    NSString *userNameStr = [NSString stringWithFormat:@"%@@CharonTVApp.com",[WSUserCenter uuid]];
    NSString *password = @"CharonTV123456";

    [[FIRAuth auth] createUserWithEmail:userNameStr
                               password:password
                             completion:^(FIRAuthDataResult * _Nullable authResult,
                                          NSError * _Nullable error) {
        if (error) {
            [self visitorRegist:userNameStr password:password];
        }else{
            FIRUser *user = authResult.user;
            [user getIDTokenWithCompletion:^(NSString * _Nullable token, NSError * _Nullable error) {
                appUserCenter.qtoken = token;
                [self logincharonTV_Request];
            }];
        }
    }];
}

- (IBAction)appleLoginAction:(id)sender {
    if (!self.checkBoxBtn.selected) {
        [WSToast simple:APPLocalized(@"請先閱讀並同意《用戶協議》，《隱私政策》和《第三方Ushare服務和隱私條款》")];
        return;
    }
    [WSToast loadingFull];
    if (@available(iOS 13.0, *)) {
        self.appleNonce = [WSTools randomNonce:32];
        ASAuthorizationAppleIDProvider *appleIDProvider = [[ASAuthorizationAppleIDProvider alloc]init];
        ASAuthorizationAppleIDRequest *request = [appleIDProvider createRequest];
        request.requestedScopes = @[ASAuthorizationScopeFullName,ASAuthorizationScopeEmail];
        request.nonce = [WSTools stringBySha256HashingString:self.appleNonce];
        ASAuthorizationController *auth = [[ASAuthorizationController alloc]initWithAuthorizationRequests:@[request]];
        auth.delegate = self;
        auth.presentationContextProvider = self;
        [auth performRequests];
    }
}



- (IBAction)googleLoginAction:(UIButton *)sender {
    [WSToast loadingFull];
    [[GIDSignIn sharedInstance] signOut];
    GIDConfiguration *config = [[GIDConfiguration alloc] initWithClientID:[FIRApp defaultApp].options.clientID];
    [GIDSignIn.sharedInstance setConfiguration:config];
    [GIDSignIn.sharedInstance signInWithPresentingViewController:self completion:^(GIDSignInResult * _Nullable signInResult, NSError * _Nullable error) {
        //error.code != -5 用戶退出
        if(error) {
            [WSToast dismiss];
            if(!signInResult.user && !signInResult.user.profile && error.code != -5) {
                [WSToast simple:WSSF(@"Login failed\n%@", error.localizedDescription)];
            };
        }
        else {
            [signInResult.user refreshTokensIfNeededWithCompletion:^(GIDGoogleUser * _Nullable user,
                                                                                   NSError * _Nullable error) {
                              if (error) {
                                  NSLog(@"%@", error.localizedDescription);
                              } else {
                                  if (user == nil) {
                                      NSLog(@"signInResult.user is nil");
                                  } else {
                                      NSLog(@"user.userID:%@", user.userID);
                                      NSLog(@"user.idToken.tokenString:%@", user.idToken.tokenString);
                                  }
                              }
                          }];
            FIRAuthCredential *credential = [FIRGoogleAuthProvider credentialWithIDToken:signInResult.user.idToken accessToken:signInResult.user.accessToken];
            [self signInFirebaseWithCredential:credential accountType:0];
        }
    }];
}

- (IBAction)facebookLoginAction:(UIButton *)sender {
    FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
    [login logOut];
    [login logInWithPermissions:@[@"public_profile", @"email"] fromViewController:self handler:^(FBSDKLoginManagerLoginResult * _Nullable result, NSError * _Nullable error) {
        if (error) {
            [WSToast simple:WSSF(@"Login failed\n%@", error.localizedDescription)];
        }
        else if(result.token) {
            [WSToast loading];
            FIRAuthCredential *credential = [FIRFacebookAuthProvider credentialWithAccessToken:[FBSDKAccessToken currentAccessToken].tokenString];
            [self signInFirebaseWithCredential:credential accountType:0];
        }
    }];
}

#pragma mark - Apple Sign

///代理主要用於展示在哪里
-(ASPresentationAnchor)presentationAnchorForAuthorizationController:(ASAuthorizationController *)controller API_AVAILABLE(ios(13.0)){
    return self.view.window;
}

-(void)authorizationController:(ASAuthorizationController *)controller didCompleteWithAuthorization:(ASAuthorization *)authorization API_AVAILABLE(ios(13.0)){
    if([authorization.credential isKindOfClass:[ASAuthorizationAppleIDCredential class]]){
        ASAuthorizationAppleIDCredential *appleIDCredential = (ASAuthorizationAppleIDCredential *)authorization.credential;
        if (appleIDCredential.identityToken == nil) {
            [WSToast simple:@"Unable to fetch identity token."];
            return;
        }
        NSString *idToken = [[NSString alloc] initWithData:appleIDCredential.identityToken encoding:NSUTF8StringEncoding];
        if (idToken == nil) {
            [WSToast simple:@"Unable to serialize id token from data"];
            return;
        }
        
        // Initialize a Firebase credential.
        FIROAuthCredential *credential = [FIROAuthProvider credentialWithProviderID:@"apple.com" IDToken:idToken rawNonce:self.appleNonce];
        [self signInFirebaseWithCredential:credential accountType:0];
    }
}

///回调失敗
-(void)authorizationController:(ASAuthorizationController *)controller didCompleteWithError:(NSError *)error API_AVAILABLE(ios(13.0)){
    NSString *errorMsg = nil;
    switch (error.code) {
        case ASAuthorizationErrorCanceled:
            errorMsg = @"用戶取消了授權請求";
            break;
        case ASAuthorizationErrorFailed:
            errorMsg = @"授權請求失敗";
            break;
        case ASAuthorizationErrorInvalidResponse:
            errorMsg = @"授權請求響應無效";
            break;
        case ASAuthorizationErrorNotHandled:
            errorMsg = @"未能處理授權請求";
            break;
        case ASAuthorizationErrorUnknown:
            errorMsg = @"授權請求失敗未知原因";
            break;
    }
    [WSToast simple:errorMsg];
}

- (void)signInFirebaseWithCredential:(FIRAuthCredential *)credential accountType:(NSInteger)accountType {
    [[FIRAuth auth] signInWithCredential:credential completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) {
        if (error || !authResult.user) {
            [WSToast simple:error.localizedDescription];
        }
        else {
            NSString *avator;
            if (authResult.user.photoURL) {
                avator = authResult.user.photoURL.absoluteString;
            }
            FIRUser *user = authResult.user;
            [user getIDTokenWithCompletion:^(NSString * _Nullable token, NSError * _Nullable error) {
                appUserCenter.qtoken = token;
                [self logincharonTV_Request];
            }];
            
        }
    }];
}

- (IBAction)checkBoxAction:(UIButton *)sender {
    sender.selected = !sender.selected;
}

//- (void)getAuthWithUserInfoFromQQ{
//
//time_t currentTime;
//time(&currentTime);
//
//if ((currentTime - loginTime) > 2)
//{
//    TencentOAuth * oauth = [[SDKCall getinstance] oauth];
//    oauth.authMode = kAuthModeClientSideToken;
//    [oauth authorize:[self getPermissions]];
////        [self askIfSetDefaultUin];
//    loginTime = currentTime;
//} else {
//    NSLog(@"慢一点，登录太频繁了(2s限频)");
//}
//
//
//
//    [[UMSocialManager defaultManager] getUserInfoWithPlatform:UMSocialPlatformType_QQ currentViewController:currViewController() completion:^(id result, NSError *error) {
//        if (error) {
//        } else {
//            [self otherWithUserInfo:result type:1];
//        }
//    }];
//}
//
//- (void)getAuthWithUserInfoFromWechat{
//    [[UMSocialManager defaultManager] getUserInfoWithPlatform:UMSocialPlatformType_WechatSession currentViewController:currViewController() completion:^(id result, NSError *error) {
//        if (error) {
//        } else {
//            [self otherWithUserInfo:result type:0];
//        }
//    }];
//}
//
//- (void)otherWithUserInfo:(id)result type:(NSInteger)type{
//    UMSocialUserInfoResponse *resp = result;
//    NSInteger time = [CCTool timeSwitchTimestamp:[resp.expiration stringWithFormat:@"yyyy-MM-dd HH:mm:ss"] andFormatter:@"yyyy-MM-dd HH:mm:ss"];
//    NSMutableDictionary *parDic = [[NSMutableDictionary alloc]init];
//    [parDic setObject:resp.accessToken?:@"" forKey:@"token"];
//    if (type == 0) {
//        [parDic setObject:@"weixin" forKey:@"type"];
//    }else{
//        [parDic setObject:@"qq" forKey:@"type"];
//    }
//    [parDic setObject:resp.openid?:@"" forKey:@"openid"];
//    [parDic setObject:resp.name?:@"" forKey:@"nickname"];
//    [parDic setObject:[NSString stringWithFormat:@"%zd",time] forKey:@"expires_in"];
//    [parDic setObject:resp.iconurl?:@"" forKey:@"avatar"];
//    [parDic setObject:[CCTool phoneUUID]?:@"" forKey:@"devicecode"];
////    [parDic setObject:@"iOS" forKey:@"channel"];
//    [parDic setObject:[CCTool getBundleID] forKey:@"package"];
//
//    NSString *vN = [CCTool versionNumber];
//    NSString *showNum = [vN stringByReplacingOccurrencesOfString:@"." withString:@""];
//    [parDic setObject:showNum?:@"" forKey:@"version"];
//    NSString *sexNum = @"0";
//    if ([resp.unionGender containsString:@"男"]) {
//        sexNum = @"1";
//    }else if ([resp.unionGender containsString:@"女"]){
//        sexNum = @"2";
//    }
//    [parDic setObject:sexNum forKey:@"sex"];
//    [self loginForAppWithModel:parDic];
//}



@end
